package Tread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Example7_Lock_Condition {
    private static final Lock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();
    private static boolean productOver = false;

    public static void main(String[] args) {
        Thread consumer = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("consumer is waiting for product's over");
                while (!productOver) {// 状态条件保护（condition predicate）
                    condition.await(); // 防止虚假唤醒
                }
                System.out.println("consumer...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        Thread product = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("Producing...");
                Thread.sleep(2000);
                productOver = true;
                System.out.println("Product is over");
                condition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        consumer.start();
        product.start();
    }
}
